const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config();

// Import routes
const userRoutes = require('./api/users');
const patternRoutes = require('./api/patterns');
const challengeRoutes = require('./api/challenges');
const progressRoutes = require('./api/progress');

// Initialize express app
const app = express();

// Middleware
app.use(cors());
app.use(express.json());

// MongoDB连接配置
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://gof23user:gof23password@localhost:27017/gof23-game';

// Connect to MongoDB
const connectDB = async () => {
  try {
    await mongoose.connect(MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('MongoDB connected');
  } catch (err) {
    console.error('MongoDB connection error:', err);
    console.log('Running in development mode without MongoDB connection');
  }
};

// Call the connect function
connectDB();

// API Routes with error handling to prevent crashes when MongoDB is not available
app.use('/api/users', (req, res, next) => {
  if (!mongoose.connection.readyState) {
    return res.status(503).json({ message: 'Database not available' });
  }
  next();
}, userRoutes);

app.use('/api/patterns', (req, res, next) => {
  if (!mongoose.connection.readyState) {
    return res.status(503).json({ message: 'Database not available' });
  }
  next();
}, patternRoutes);

app.use('/api/challenges', (req, res, next) => {
  if (!mongoose.connection.readyState) {
    return res.status(503).json({ message: 'Database not available' });
  }
  next();
}, challengeRoutes);

app.use('/api/progress', (req, res, next) => {
  if (!mongoose.connection.readyState) {
    return res.status(503).json({ message: 'Database not available' });
  }
  next();
}, progressRoutes);

// Serve static assets in production
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../client/build')));
  
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '../client', 'build', 'index.html'));
  });
}

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Server error', error: err.message });
});

// Start server
const PORT = process.env.PORT || 9001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 